package cn.lls.controller.ca;

import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import cn.lls.entity.company.DepartmentEntity;
import cn.lls.entity.sys.EmployeeBaseEntity;
import cn.lls.req.company.ConditionSearchDepartmentReq;
import cn.lls.service.IDepartmentService;
import cn.lls.service.IEmployeeBaseService;
import cn.lls.vo.company.DepartmentInfo;
import cn.lls.vo.company.DepartmentInfoVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.stream.Collectors;

/**
 * <p>
 *  部门信息控制器
 * </p>
 *
 * @author 划水艺术家
 * @since 2022-11-15
 */
@RestController
@RequestMapping("/ca/department")
@Api(tags = "公司部门信息控制器")
@Slf4j
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IEmployeeBaseService employeeBaseService;

    @PostMapping("/info")
    @ApiOperation(value = "分页条件查询本公司部门信息", notes = "分页条件查询本公司部门信息",
            response = R.class, httpMethod = "POST")
    public R getDepartmentInfoByPageAndCondition(
            @RequestBody @Validated ConditionSearchDepartmentReq conditionSearchDepartmentReq,
                     BindingResult bindingResult){
        conditionSearchDepartmentReq.setDepartmentName(conditionSearchDepartmentReq.getDepartmentName().trim());
        log.info("conditionReq = {}", conditionSearchDepartmentReq);

        LambdaQueryWrapper<DepartmentEntity> queryWrapper =  new LambdaQueryWrapper<>();
        queryWrapper.eq(DepartmentEntity::getCompanyId, conditionSearchDepartmentReq.getCompanyId());
        if (StringUtils.isNotBlank(conditionSearchDepartmentReq.getDepartmentName())){
            queryWrapper.like(DepartmentEntity::getDepartmentName, conditionSearchDepartmentReq.getDepartmentName());
        }
        IPage<DepartmentEntity> page = new Page<>(conditionSearchDepartmentReq.getCurrentPage(), conditionSearchDepartmentReq.getPageSize());
        IPage<DepartmentEntity> pageV = departmentService.page(page, queryWrapper);

        DepartmentInfoVO departmentInfoVO = new DepartmentInfoVO();
        departmentInfoVO.setTotal(pageV.getTotal());
        departmentInfoVO.setRecords(pageV.getRecords().stream().map((item)->{
            DepartmentInfo info = new DepartmentInfo();
            BeanUtils.copyProperties(item, info);
            LambdaQueryWrapper<EmployeeBaseEntity> qw = new LambdaQueryWrapper<>();
            qw.eq(EmployeeBaseEntity::getDepartmentId, item.getDepartmentId());
            info.setDepartmentPeopleCount(employeeBaseService.count(qw));
            info.setCreateTime(item.getCreateTime().toString());
            return info;
        }).collect(Collectors.toList()));
        return R.success(departmentInfoVO);
    }


    @GetMapping("/{companyId}")
    @ApiOperation(value = "获取所有部门信息", notes = "获取所有部门信息",
            response = R.class, httpMethod = "GET")
    public R getAllDepartment(
            @ApiParam(required = true, value = "部门Id")
            @PathVariable("companyId")
            @NotEmpty(message = "必须具备公司Id") Long companyId){
        LambdaQueryWrapper<DepartmentEntity> queryWrapper =  new LambdaQueryWrapper<>();
        queryWrapper.eq(DepartmentEntity::getCompanyId, companyId);
        return R.success(departmentService.list(queryWrapper));
    }


    @ApiOperation(value = "添加部门信息", notes = "添加部门信息", response = R.class, httpMethod = "POST")
    @PostMapping
    public R addDepartment(
            @Validated @RequestBody DepartmentEntity departmentEntity,
            BindingResult bindingResult){
        try {
            if(departmentService.save(departmentEntity))
                return R.success();
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail(ResultCode.DATABASE_ERROR, ResultCode.DATA_ERROR.getMessage());
        }
        return R.fail(ResultCode.DATABASE_ERROR, ResultCode.DATA_ERROR.getMessage());
    }

    @ApiOperation(value = "删除部门", notes = "根据Id删除部门，若该部门有人则无法删除", response = R.class, httpMethod = "DELETE")
    @DeleteMapping("/{departmentId}")
    public R delPermission(
            @ApiParam(required = true, value = "部门Id")
            @PathVariable("departmentId")
            @NotEmpty(message = "必须具备部门Id") Long departmentId){
        departmentService.delDepartment(departmentId);
        return R.success();
    }

    @ApiOperation(value = "更改部门信息", notes = "更改部门信息", response = R.class, httpMethod = "PUT")
    @PutMapping
    public R updateDepartment(
            @Validated @RequestBody DepartmentEntity departmentEntity,
            BindingResult bindingResult){
        LambdaUpdateWrapper<DepartmentEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DepartmentEntity::getDepartmentId, departmentEntity.getDepartmentId());
        try {
            if (departmentService.update(departmentEntity, updateWrapper))
                return R.success();
        } catch (Exception e) {
            return R.fail(ResultCode.DATA_ERROR, ResultCode.DATA_ERROR.getMessage());
        }
        return R.fail(ResultCode.DATA_ERROR, ResultCode.DATA_ERROR.getMessage());
    }
}

